package com.oasistudio.ads.expert.banner;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.view.View;

/**
 * 存储并管理已经展现过的广告历史。
 */
public class AdHistory {
	public static final Map<String, List<Bitmap>> AdHistory = new HashMap<String, List<Bitmap>>();
	public static final Map<String, List<AtomicInteger>> AdHistoryCount = new HashMap<String, List<AtomicInteger>>();

	public static void saveAd(String union, View adView) {
		try {
//			System.out.println("**************************Adwo.AdListener.onReceivedAd() AdwoAdView = " + adView);
//			System.out.println("**************************Adwo.AdListener.onReceivedAd() AdwoAdView.width = "
//					+ adView.getWidth());
//			System.out.println("**************************Adwo.AdListener.onReceivedAd() AdwoAdView.height = "
//					+ adView.getHeight());
//			System.out.println("**************************Adwo.AdListener.onReceivedAd() AdwoAdView.drawingCache = "
//					+ adView.getDrawingCache());
			int width = adView.getWidth();
			int height = adView.getHeight();
			if (width > 0 && height > 0) {
				long time = System.currentTimeMillis();
				Bitmap image = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
				adView.draw(new Canvas(image));
				// 如果是不同的图片，就存储
				// boolean same = false;
				List<Bitmap> adImages = AdHistory.get(union);
				if (adImages == null) {
					adImages = new ArrayList<Bitmap>();
					AdHistory.put(union, adImages);
					AdHistoryCount.put(union, new ArrayList<AtomicInteger>());
				}
				for (int i = 0; i < adImages.size(); i++) {
					Bitmap temp = adImages.get(i);
					ByteBuffer buffer1 = ByteBuffer.allocate(temp.getHeight() * temp.getRowBytes());
					temp.copyPixelsToBuffer(buffer1);

					ByteBuffer buffer2 = ByteBuffer.allocate(image.getHeight() * image.getRowBytes());
					image.copyPixelsToBuffer(buffer2);

					if (Arrays.equals(buffer1.array(), buffer2.array())) {
//						System.out.println(union + ":图片是相同的，不用再存储了。");
//						System.out.println(union + ":比较图片耗时：" + (System.currentTimeMillis() - time));
//						System.out.println(union + ":图片是相同的，已展现次数："
//								+ AdHistoryCount.get(union).get(i).incrementAndGet());
//						// same = true;
						AdHistoryCount.get(union).get(i).incrementAndGet();
						return;
					}
				}
				adImages.add(image);
				AdHistoryCount.get(union).add(new AtomicInteger(1));
				try {
					String sdcardPath = getExternalStoragePath();
					System.out.println(union + ":sdcardPath = " + sdcardPath);
					String filename = sdcardPath + "/adExperts/" + union + "/" + System.currentTimeMillis() + ".png";
					File file = new File(filename);
					if (!file.exists() && !file.getParentFile().exists()) {
						file.getParentFile().mkdirs();
					}
					FileOutputStream out = new FileOutputStream(filename);
					image.compress(Bitmap.CompressFormat.PNG, 90, out);
//					System.out.println(union + ":存储广告图片耗时：" + (System.currentTimeMillis() - time));
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 获取SdCard路径
	 */
	public static String getExternalStoragePath() {
		// 获取SdCard状态
		String state = android.os.Environment.getExternalStorageState();
		// 判断SdCard是否存在并且是可用的
		if (android.os.Environment.MEDIA_MOUNTED.equals(state)) {
			if (android.os.Environment.getExternalStorageDirectory().canWrite()) {
				return android.os.Environment.getExternalStorageDirectory().getPath();
			}
		}
		return null;
	}

	/** 删除历史数据 */
	public static void clearHistory() {
		String sdcardPath = getExternalStoragePath();
		String filename = sdcardPath + "/adExperts";
		try{
			del(filename);
		}catch(Exception e){
			e.printStackTrace();
		}
	}

	public static void del(String filepath) throws IOException {
		File f = new File(filepath);// 定义文件路径
		if (f.exists() && f.isDirectory()) {// 判断是文件还是目录
			if (f.listFiles().length == 0) {// 若目录下没有文件则直接删除
				f.delete();
			} else {// 若有则把文件放进数组，并判断是否有下级目录
				File delFile[] = f.listFiles();
				int i = f.listFiles().length;
				for (int j = 0; j < i; j++) {
					if (delFile[j].isDirectory()) {
						del(delFile[j].getAbsolutePath());// 递归调用del方法并取得子目录路径
					}
					delFile[j].delete();
				}
			}
		}
	}
}
